package com.lanou.filter;


import javax.servlet.*;
import java.io.IOException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebFilter("/admin/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain Chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();

        // 如果session里没有登录信息，无法自动登录，重定向到登录页，让用户手动登录
        if (session.getAttribute("username" )== null){
            resp.getWriter().println("请先登录！");
            resp.sendRedirect("/login.jsp");
            return;
        }
        String username = (String) session.getAttribute("username");

        // 检查session中的登录信息是否正确
        if (username !=null ){

            Chain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {

    }
}
